<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片样式 -->
    <el-card>
      <el-alert show-icon :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning"></el-alert>
      <!-- 选择商品分类区 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品的级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedKeys"
            :options="catelist"
            :props="cascaderProps"
            @change="handleChange"
            clearable
            
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数的 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            size="mini"
            @click="addParamsDialogVisible = true"
          >添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 循环渲染Tag标签 -->
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">{{item}}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>

            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-delete"
                  @click="showDeleteDialog(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            @click="addParamsDialogVisible = true"
            :disabled="isBtnDisabled"
            size="mini"
          >添加属性</el-button>
          <!-- 静态属性 -->
          <el-table :data="onlyTableData" border stripe>
             <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 循环渲染Tag标签 -->
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">{{item}}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-delete"
                  @click="showDeleteDialog(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      @close="addDialogClosed"
      :visible.sync="addParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="addParamsForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改动态参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      @close="editDialogClosed"
      :visible.sync="editParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="editParamsForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品列表数据
      catelist: [],
      //级联选择框配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //级联选择框双向绑定数据
      selectedKeys: [],
      //被激活的页签名称  first表示默认第一个
      activeName: "many",
      //动态数据存放
      manyTableData: [],
      //静态数据存放
      onlyTableData: [],

      addParamsDialogVisible: false,

      editParamsDialogVisible: false,
      //验证提交的表
      addParamsForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入修改的参数",
            trigger: "blur",
          },
        ],
      },
      //修改的验证
      editParamsForm: {
        attr_name: "",
      },
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入修改的参数",
            trigger: "blur",
          },
        ],
      },
    };
  },
  //注册组件
  components: {},
  //计算机属性
  computed: {
    //判断按钮是否需要被禁用
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true;
      }
      return false;
    },
    //当前选中的三级Id
    cateId() {
      if (this.selectedKeys.length == 3) {
        return this.selectedKeys[2];
      }
      return null;
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
  created() {
    //获取所有商品分类列表
    this.getCateList();
  },

  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类数据失败");
      }

      this.catelist = res.data;
    },
    //级联选择框改变触发事件
    handleChange() {
      this.getParamsDate();
    },
    //获取选项卡参数请求
    async getParamsDate() {
      //判断选择的是不是三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }

      //根据选中的数据ID发起请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      }

      //el-tag 下面的标签

      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        //添加boolean 控制文本框显示
        item.inputVisible = false;
        //文本框输入的值
        item.inputValue = "";
      });

      if (this.activeName === "many") {
        this.manyTableData = res.data;
        console.log(this.manyTableData);
      } else {
        this.onlyTableData = res.data;
      }
    },
    //tabs页签实现选项卡切换
    handleClick() {
      this.getParamsDate();
    },
    //提交添加的数据
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        );

        if (res.meta.status !== 201) {
          this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        this.addParamsDialogVisible = false;
        this.getParamsDate();
      });
    },
    //清空对话框里面的值
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //修改按钮的对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("获取参数失败");
      }
      //获取到当前参数的所有信息
      this.editParamsForm = res.data;
      this.editParamsDialogVisible = true;
    },
    //提交修改的新值
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("修改失败");
        }
        this.$message.success("修改成功");

        this.editParamsDialogVisible = false;
        this.getParamsDate();
      });
    },
    //清空对话框里面的值
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    async showDeleteDialog(attr_id) {
      const confirmResult = await this.$confirm("将删除该属性?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);

      //用户取消删除
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      //删除接口
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );

      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }

      this.$message.success("删除成功！");

      this.getParamsDate();
    },

    //文本框失去焦点或按下enter
   async handleInputConfirm(row) {
      if (row.inputValue.trim().leng === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }

      //如果没有return 则先添加在attr_vals数组中
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      this.saveAttrVals(row)
    },
    // //发送请求添加到后端
    async saveAttrVals(row){
           
    const {data: res} = await  this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })

      if(res.meta.status !==200) {
        return this.$message.error('修改失败')
      }

      this.$message.success('修改成功')
    },
    //切换文本输入框
    showInput(row) {
      row.inputVisible = true;
      //让文本框自动获得·焦点
      //$nextTick当页面被重新渲染后,才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除对应的tag标签
    handleClose(i, row){
      //会修改原数组splice
        row.attr_vals.splice(i, 1)
        this.saveAttrVals(row)
    }
  },
};
</script>
<style lang='css' scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
}
.input-new-tag {
  margin-left: 10px;
  width: 120px;
}
</style>